<?php
require_once 'MySQLConnectionPool.php';

class DbConnPool {
	static public $DEFAULT_PORT = 3306;

	private $writer;
	private $readers;
	private $maxReaderIndex;
	private $dbUser;
	private $dbPwd;
	private $dbName;
	private $dbPort;

	public function __construct($configFile) {
		$config= ConfigReaderFactory::getInstance()->getConfigReader($configFile)->getConfig();
		$this->writer = (string) $config->db->writer[0];
		$this->dbUser = (string) $config->db->user[0];
		$this->dbPwd = (string) $config->db->pwd[0];
		$this->dbName = (string) $config->db->name[0];
		$this->dbPort = (string) $config->db->port[0];
		foreach ($config->db->readers->reader as $reader) {
			$this->readers[] = (string) $reader;
		}
		$this->maxReaderIndex = count($this->readers) - 1;
	}
	
	public function getReadConn() {
		return $this->_getConn($this->readers[rand(0, $this->maxReaderIndex)]);		
	}
	
	public function getWriteConn() {
		return $this->_getConn($this->writer);
	}
	
	protected function _getConn($dbHost) {
		$tmp = explode(':', $dbHost);
		$host = $tmp[0];
		$port = isset($tmp[1]) ? $tmp[1] : self::$DEFAULT_PORT;

		return MySQLConnectionPool::getConnection($host, $port, $this->dbName, $this->dbUser, $this->dbPwd);		
	}
	
	public function clearPool() {
		MySQLConnectionPool::clearPool();
	}
}
?>
